import React from 'react'
import {
    Button,
    message,
    Modal
} from 'antd'
import Table from '../../components/Table'
import {
    FormModal
} from '../../components/ModalForm'

import SystemUserformModalForm from './SystemUser-form'

import 'whatwg-fetch'
import API from '../../axios/api'
import { getUser } from '../../utils/Session'
import {withRouter} from "react-router-dom";
import {inject, observer} from "mobx-react";
require('es6-promise').polyfill();
const confirm = Modal.confirm


const columns = [
    { dataIndex: 'LoginName', title: '登录名', width: 220,},
    { dataIndex: 'RealName', title: '姓名', width: 200,},
    { dataIndex: 'CellPhone', title: '手机号', width: 200,},
    { dataIndex: 'EmailAddress', title: '邮箱', width: 200,},
    { dataIndex: 'RudderName', title: '分舵', width: 200,},
    { dataIndex: 'RoleName', title: '角色', width: 200,},
]
@withRouter @inject('appStore') @observer
class SystemUser extends React.Component {
    constructor(props) {
        super(props)
        const {user, rudder, rudderList} = this.props.appStore
        let newlist = [...rudderList]
        if(newlist[0] && newlist[0].mean != '总舵'){
            newlist.unshift({
                mean: "总舵",
                value: "-"
            })
        }
       
        this.state = {
            rudderList: newlist,
            tData: [],
            item: {},
            loading: true,
            modalShow: false,
            modalShowEdit: false,
            initUserList: [],
            roleList: [],
            editUserinfo:{},
            Page: 1,
            Pages:1,
        }
    }

    // 获取表格数据
    fetchTableData =  async () => {
        let parms = {
            Page:this.state.Page,
            PageSize: 10,
        }
        await API.fetchCmsUserList(parms).then((res) => {
            if(res.Code === 200) {
                this.setState({
                    tData: res.Data.List,
                    Pages:res.Data.Pages
                });
            }
            this.setState({
                loading: false
            });
        })
    }

    initRoleList =  async () => {
        let params = {
            Id: ''
        }
        let roleList = []
        await API.fetchRoles(params).then((res) => {
            if(res.Code === 200) {
                res.Data && res.Data.map(item => roleList.push({value: item.Id, mean: item.RoleName}))
                this.setState({
                    roleList:roleList
                })
            }
        })
    }

    initUserList =  async () => {
        let params = {
            Page: 1,
            PageSize: 1000
        }
        await API.fetchUserPages(params).then((res) => {
            let _initUserList = []
            if(res.Code === 200) {
                res.Data.List && res.Data.List.map(item => _initUserList.push({key: item.Id, value: item.NickName}))
                this.setState({
                    initUserList: _initUserList
                })
            }
        })
    }
    componentWillReceiveProps(nextProps){
        const {user, rudder, rudderList} = this.props.appStore
        let newlist = [...rudderList]
        if(newlist[0] && newlist[0].mean != '总舵'){
            newlist.unshift({
                mean: "总舵",
                value: "-"
            })
        }
        this.setState({
            rudderList:newlist
        })
    }
    componentDidMount() {
      

        this.fetchTableData()
    }

    componentWillMount() {
        this.initRoleList()
        this.initUserList()
    }

    add = () =>{
        this.setState({
            modalShow: true
        })
    }

    onOk = (param) =>{
        API.editCmsUser(param).then(res =>{
            if(res.Code === 200)
            {
                message.success('添加成功')
                this.onCancel()
                this.fetchTableData()
            }
            else message.error(res.Message)
        })
    }

    onCancel = () =>{
        this.setState({
            modalShow: false,
            modalShowEdit:false
        })
    }

    onOkEdit = (param) =>{
        let that = this
         param.userid = this.state.editUserinfo.Id
        this.setState({
            modalShowEdit: false
        })
        let RoleName = ''
         this.state.roleList.map(function (item) {
            if(item.value == param.RoleId){
                RoleName =  item.mean
            }
          })
        API.fetchUpateCmsUser(param).then((res) => {
            if(res.Code === 200) {
                message.success('修改成功')
                that.fetchTableData()
                //let newdata = [...that.state.tData]
                // newdata.map(function (item) {
                //    if( item.Id == that.state.editUserinfo.Id){
                //     item.CellPhone = param.CellPhone
                //     item.RealName = param.RealName    
                //     item.EmailAddress = param.EmailAddress 
                //     item.RoleName = RoleName
                //    }
                //    return item;
                //   })
                //   that.setState({
                //     tData:newdata
                //   })
            }
        })
    }

    onCancelEdit = () =>{
        this.setState({
            modalShowEdit: false
        })
    }

    tableAction = (actionKey, item) => {
        if (actionKey === 'edit') {
            console.log(item)
            this.setState({
                editUserinfo:item,
                modalShowEdit: true
            })
          
        } else if (actionKey === 'delete') {
            confirm({
                title: '提示',
                content: '确定删除吗',
                onOk: () => {
                    this.handerDel(item, 0).then(res => {
                        if(res.Code === 200) message.success('删除成功')
                        else message.error(res.Message)
                    })
                    this.fetchTableData()
                },
                onCancel() {}
            })
        }
    }

    onPageChange = (e) =>{
        this.setState({
            Page:e,
        },()=>{
            this.fetchTableData()
        })
    }



    handerDel(item, status){
        return API.delRole({Id: item.Id, Status: status})
    }
    searchValues(values){
        return this.state.initUserList.filter(item => item.NickName.includes(values))
    }

    fields = () => {
        let _permissionStatus = PermissionStatus;
        return  [
            { label: '登录名', type: 'input', name: 'LoginName',
                options: {
                    rules: [
                        { required: true, message: '登录名必填!',}
                    ]
                }
            },
            { label: '密码', type: 'password', name: 'Password',
                options: {
                    rules: [
                        { required: true, message: '密码必填!',}
                    ]
                }
            },
            {
                label: '用户角色',
                type: 'select',
                name: 'RoleId',
                items: () => this.state.roleList,
                options: {
                    rules: [{
                        required: true,
                        message: '必选!',
                    }]
                }
            },
            {
                label: '分舵',
                type: 'select',
                name: 'RudderId',
                items: () => this.state.rudderList,
                options: {
                    rules: [{
                        required: true,
                        message: '必选!',
                    }]
                }
            },
            { label: '姓名', type: 'input', name: 'RealName',},
            { label: '手机号', type: 'input', name: 'CellPhone',},
            { label: '邮箱', type: 'input', name: 'EmailAddress',},
        ]
    }

    render() {
        return (
            <div id="wrap">
                <div style={{ paddingTop: 10 }}>
                    <Button type="primary" onClick={this.add} >添加</Button>
                </div>
                <div className="tableBox">
                    <div style={{ paddingTop: 10 }}>
                        <Table
                            onCtrlClick={ this.tableAction }
                            pagination={ true }
                            pageSize={10}
                            header={ columns }
                            data={ this.state.tData }
                            loading={ this.state.loading }
                            action={row => [
                                { key: 'edit', name: '编辑', color: 'blue', icon: 'highlight'},
                            ]}
                            total={this.state.Pages}
                            onChange={this.onPageChange}
                            currentPage={this.state.Page}
                            scroll={{y: 385 }}
                        />
                    </div>
                </div>
                <FormModal
                    modalKey="add"
                    visible={this.state.modalShow}
                    title="添加"
                    fields={this.fields()}
                    onOk={this.onOk}
                    onCancel={this.onCancel}
                    okText="保存"
                    searchValues={this.searchValues}
                />

                {/**编辑 */}
                <SystemUserformModalForm
                    modalKey="add"
                    visible={this.state.modalShowEdit}
                    title="添加"
                    onOk={this.onOkEdit}
                    onCancel={this.onCancel}
                    okText="保存"
                    RoleList={this.state.roleList}
                    userdata={this.state.editUserinfo}
                    searchValues={this.searchValues}
                />
            </div>
        )
    }
}
export default SystemUser
